package com.moive.news.tqnewsapplication.ui.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.moive.news.tqnewsapplication.R;
import com.moive.news.tqnewsapplication.base.AppManager;
import com.moive.news.tqnewsapplication.base.BaseActivity;
import com.moive.news.tqnewsapplication.event.SenEvent;
import com.moive.news.tqnewsapplication.guide.SplashActivity;
import com.moive.news.tqnewsapplication.networks.BaseApi;
import com.moive.news.tqnewsapplication.okmanager.OkManagerCallback;
import com.moive.news.tqnewsapplication.push.ExampleUtil;
import com.moive.news.tqnewsapplication.push.LocalBroadcastManager;
import com.moive.news.tqnewsapplication.push.TagAliasOperatorHelper;
import com.moive.news.tqnewsapplication.runtimepermissions.PermissionsManager;
import com.moive.news.tqnewsapplication.runtimepermissions.PermissionsResultAction;
import com.moive.news.tqnewsapplication.ui.fragment.FragmentController;
import com.moive.news.tqnewsapplication.utils.LogUtil;
import com.moive.news.tqnewsapplication.utils.PreferenceUtil;
import com.moive.news.tqnewsapplication.utils.RxDeviceTool;
import com.moive.news.tqnewsapplication.utils.RxDialogSureCancel;
import com.moive.news.tqnewsapplication.utils.ToastUtils;
import com.umeng.analytics.MobclickAgent;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import okhttp3.Call;

import static android.view.KeyEvent.KEYCODE_BACK;

public class MainActivity extends BaseActivity {

    @BindView(R.id.activity_main)
    RelativeLayout activityMain;
    @BindView(R.id.ivIconHome)
    ImageView ivIconHome;
    @BindView(R.id.tvTextHome)
    TextView tvTextHome;
    @BindView(R.id.homeBottomRadioButton_ll)
    RelativeLayout homeBottomRadioButtonLl;
    @BindView(R.id.ivIconVideo)
    ImageView ivIconVideo;
    @BindView(R.id.tvTextVideo)
    TextView tvTextVideo;
    @BindView(R.id.infoBottomRadioButton_ll)
    RelativeLayout infoBottomRadioButtonLl;
    @BindView(R.id.ivIconAttention)
    ImageView ivIconAttention;
    @BindView(R.id.tvTextAttention)
    TextView tvTextAttention;
    @BindView(R.id.dyBottomRadioButton_ll)
    RelativeLayout dyBottomRadioButtonLl;
    @BindView(R.id.ivIconMe)
    ImageView ivIconMe;
    @BindView(R.id.tvTextMe)
    TextView tvTextMe;
    @BindView(R.id.meBottomRadioButton_ll)
    RelativeLayout meBottomRadioButtonLl;
    @BindView(R.id.main_bottom)
    LinearLayout mainBottom;
    @BindView(R.id.fl_content)
    FrameLayout flContent;
    @BindView(R.id.meBottomRadioButton_img)
    RelativeLayout meBottomRadioButtonImg;
    @BindView(R.id.tt)
    TextView tt;
    private FragmentController mController;
    private View lastSelectedIcon;
    private View lastSelectedText;
    private String isfrom = "0";
    public static boolean isForeground = false;
    String imei = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        init();
    }
    private void init() {
        check();
        registerMessageReceiver();  // used for receive msg
        EventBus.getDefault().register(MainActivity.this);
        mController = FragmentController.getInstance(this, R.id.fl_content, true);
        mController.showFragment(0);
        setListener();
    }
    private void upIMEI() {
        //上传手机唯一标识符
        imei = RxDeviceTool.getIMEI(MainActivity.this);
        OkHttpUtils.post()
                .url(BaseApi.UPIMEI)
                .addParams("IMEI",imei)
                .build().execute(new OkManagerCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
            }
            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                try {
                    JSONObject j=new JSONObject(response);
                    LogUtil.e(TAG,j.toString());
                    if (j.getInt("code")==0){
                        PreferenceUtil.put("isimei","1");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    protected void setListener() {
        for (int i = 0; i < mainBottom.getChildCount(); i++) {
            if (i == 0) {
                //默认选中首页
                setSelectIcon(ivIconHome, tvTextHome);
            }
            final int position = i;
            mainBottom.getChildAt(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (lastSelectedIcon != null) lastSelectedIcon.setSelected(false);
                    if (lastSelectedText != null) lastSelectedText.setSelected(false);
                    RelativeLayout rl = (RelativeLayout) v;
                    ImageView icon = (ImageView) rl.getChildAt(0);
                    TextView text = (TextView) rl.getChildAt(1);
                    mController.showFragment(position);
                    setSelectIcon(icon, text);
                }
            });
        }
    }

    public void setSelectIcon(ImageView iv, TextView tv) {
        iv.setSelected(true);
        tv.setSelected(true);
        lastSelectedIcon = iv;
        lastSelectedText = tv;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mController.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
    }

    private void finduserinfo() {
        String token = "";
        token = PreferenceUtil.getString("token", "");
        if (TextUtils.isEmpty(token)) {
            return;
        } else {
            OkHttpUtils.post()
                    .url(BaseApi.FINDINFO)
                    .addParams("token", token)
                    .build().execute(new OkManagerCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    super.onError(call, e, id);
                }
                @Override
                public void onResponse(String response, int id) {
                    super.onResponse(response, id);
                    try {
                        LogUtil.i(TAG, "response=" + response.toString());
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.optInt("code") == 0) {
                            JSONObject jsonObject1=jsonObject.getJSONObject("data");
                            String userid=jsonObject1.getString("id");
                            String telephone=jsonObject1.getString("telephone");
                            String headImg=jsonObject1.getString("headimg");
                            String signature=jsonObject1.getString("signature");
                            int sex=jsonObject1.getInt("sex");
                            String nickName=jsonObject1.getString("nickname");
                            PreferenceUtil.put("id",userid);
                            PreferenceUtil.put("telephone",telephone);
                            PreferenceUtil.put("headImg",headImg);
                            PreferenceUtil.put("sex",sex+"");
                            PreferenceUtil.put("nickName",nickName);
                            PreferenceUtil.put("signature",signature);
                            // 调用 Handler 来异步设置别名
                            mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, userid));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.d(TAG, "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    TagAliasOperatorHelper.TagAliasBean tagAliasBean = new TagAliasOperatorHelper.TagAliasBean();
                    tagAliasBean.setAction(2);
                    tagAliasBean.setAlias( (String) msg.obj);
                    JPushInterface.setAlias(MainActivity.this,1001,tagAliasBean.getAlias());
                    break;
                default:
                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };
    private void check() {
        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(MainActivity.this,new String[]{
                Manifest.permission.READ_PHONE_STATE
        }, new PermissionsResultAction() {
            @Override
            public void onGranted() {
                if (PreferenceUtil.getString("isimei","").equals("0")){
                    upIMEI();
                }
            }
            @Override
            public void onDenied(String permission) {
                ToastUtils.ShortToast("用户拒绝授权");
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataSynEvent(SenEvent event) {
        String msg = event.getmMsg();
        LogUtil.i(TAG, "msg=" + msg);
        if (msg.equals("1")) {
            mController.showFragment(3);
            setSelectIcon(ivIconAttention, tvTextAttention);
        }else if (msg.equals("2")){
            mController.showFragment(0);
//            setSelectIcon(ivIconHome,tvTextHome);
        }
    }
    @Override
    protected void onResume() {
        isForeground = true;
        finduserinfo();
        super.onResume();
    }
    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
//            JCVideoPlayer.releaseAllVideos();
    }
    //for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
    }
    public class MessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                    String messge = intent.getStringExtra(KEY_MESSAGE);
                    String extras = intent.getStringExtra(KEY_EXTRAS);
                    StringBuilder showMsg = new StringBuilder();
                    showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                    if (!ExampleUtil.isEmpty(extras)) {
                        showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                    }
                    setCostomMsg(showMsg.toString());
                }
            } catch (Exception e){
            }
        }
    }
    private void setCostomMsg(String msg){
        ToastUtils.LongToast(msg);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            exit();
        }
        return super.onKeyDown(keyCode, event);
    }
    private void exit(){
        final RxDialogSureCancel rxDialogSureCancel = new RxDialogSureCancel(MainActivity.this);//提示弹窗
        rxDialogSureCancel.getTitleView().setText("是否退出");
        rxDialogSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onKillProcess(MainActivity.this);
                AppManager.getAppManager().finishAllActivity();
                AppManager.getAppManager().AppExit(MainActivity.this);
            }
        });
        rxDialogSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rxDialogSureCancel.cancel();
            }
        });
        rxDialogSureCancel.show();
    }
}
